package com.android.fragmentdemo.defineviews
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.res.ResourcesCompat
import com.android.fragmentdemo.R

class DefineLinearLayout @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : LinearLayoutCompat(context, attributeSet) {

    private val mPaint1 by lazy {
        Paint().apply {
            isDither = true
            isAntiAlias = true
            color = context.resources.getColor(R.color.color_673ab7)
        }
    }

    private var drawBg = false

    private var cornerValue = context.resources.getDimension(R.dimen.dp_10)

    init {
        setLayerType(View.LAYER_TYPE_HARDWARE, null)
    }

    override fun dispatchDraw(canvas: Canvas) {
        canvas.apply {
            val borderValue = if (drawBg) {
                context.resources.getDimension(R.dimen.dp_5)
            } else {
                0F
            }

            if (drawBg) {
                val drawable =
                    ResourcesCompat.getDrawable(resources, R.drawable.layout_item_bg, null)
                drawable?.let {
                    it.setBounds(
                        0,
                        0,
                        measuredWidth,
                        measuredHeight
                    )
                    it.draw(this@apply)
                }
            }

            drawRoundRect(
                0F + borderValue,
                0F + borderValue,
                measuredWidth.toFloat() - borderValue,
                measuredHeight.toFloat() - borderValue,
                cornerValue,
                cornerValue,
                mPaint1
            )
        }
        super.dispatchDraw(canvas)
    }

    fun updateDrawBgFlag(flag: Boolean) {
        drawBg = flag
        invalidate()
    }
}